package com.shujia.flink.transform;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Demo05Reduce {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<String> lineDS = env.socketTextStream("master", 8888);

        // 将数据切分，一个单词变成一行数据并转换成KV格式
        DataStream<Tuple2<String, Integer>> kvDS = lineDS.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                for (String word : value.split(",")) {
                    out.collect(Tuple2.of(word, 1));
                }
            }
        });

        KeyedStream<Tuple2<String, Integer>, String> grpDS = kvDS.keyBy(kv -> kv.f0);

        DataStream<Tuple2<String, Integer>> sumDS = grpDS.reduce(new ReduceFunction<Tuple2<String, Integer>>() {
            /**
             * 如果第一条数据进来，则不会触发reduce方法的执行
             * 如果第两条数据进来，则一条赋给value1，另一条赋给value2，就会执行reduce方法，返回一个计算的结果
             * 如果第三条数据进来，则上一次的计算结果会赋给value1，进来的这条数据赋给value2，触发reduce方法执行并计算新的结果
             * 以此类推
             *
             * 由于会使用上一次的计算结果，故这是一个有状态的操作
             * @param value1
             * @param value2
             * @return
             * @throws Exception
             */
            @Override
            public Tuple2<String, Integer> reduce(Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) throws Exception {
                System.out.println(value1);
                System.out.println(value2);
                // 实现累加的聚合操作
                return Tuple2.of(value1.f0, value1.f1 + value2.f1);
            }
        });

        sumDS.print();

        env.execute();
    }
}
